package com.service.back.impl;

import com.alibaba.fastjson.JSONObject;
import com.conf.BackAdminLogin;
import com.conf.BaseServlet;
import com.model.*;
import com.service.back.TOrderInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TOrderInfoServiceImpl extends BaseServlet implements TOrderInfoService {
    @Override
    public List<TOrderInfo> selectOrderInfoList(JSONObject jsonObject, Integer type) {
        TAdminInfo adminInfo = BackAdminLogin.getAdminInfo();
        if(adminInfo.getTaiGroupId() == null){
            return null;
        }
        return tOrderInfoMapper.selectOrderInfoList(
                jsonObject.getString("tuiPhone"),
                jsonObject.getString("startTime"),
                jsonObject.getString("endTime"),
                jsonObject.getInteger("centerId"),
                jsonObject.getInteger("tProxyInfoId"),
                jsonObject.getInteger("tuiUserId"),
                jsonObject.getString("stockIdName"),
                jsonObject.getInteger("toiStatus"),
                type,
                adminInfo.getTaiGroupId(),
                adminInfo.getTaiRelationId());
    }

    @Override
    public Map<String, Object> getOtherResultMap() {
        Map<String, Object> map = new HashMap<>();
        TAdminInfo adminInfo = BackAdminLogin.getAdminInfo();
        /////  adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId()
        //运营中心
        if(adminInfo.getTaiGroupId() == null){
            map.put("centerCount", null);
        }else{
            String centerCount = tOperationCenterMapper.getCenterCount(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("centerCount", centerCount);
        }


        //代理
        if(adminInfo.getTaiGroupId() == null){
            map.put("proxyCount", null);
        }else{
            String proxyCount = tProxyInfoMapper.getProxyCount(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("proxyCount", proxyCount);
        }


        //用户
        if(adminInfo.getTaiGroupId() == null){
            map.put("userCount", null);
        }else{
            String userCount = tUserInfoMapper.getUserCount(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("userCount", userCount);
        }


        //订单数量
        if(adminInfo.getTaiGroupId() == null){
            map.put("orderCount", null);
        }else{
            String orderCount = tOrderInfoMapper.getOrderCount(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("orderCount", orderCount);
        }


        //交易总额
        if(adminInfo.getTaiGroupId() == null){
            map.put("orderSumMoney", null);
        }else{
            String orderSumMoney = tOrderInfoMapper.getOrderSumMoney(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("orderSumMoney", orderSumMoney);
        }


        //提现金额
        if(adminInfo.getTaiGroupId() == null){
            map.put("takeMoney", null);
        }else{
            Double userTakeMoney = tTakeMoneyMapper.getUserTakeMoney(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            Double proxyTakeMoney = tTakeMoneyMapper.getProxyTakeMoney(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            Double centerTakeMoney = tTakeMoneyMapper.getCenterTakeMoney(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            BigDecimal user = new BigDecimal(userTakeMoney);
            BigDecimal proxy = new BigDecimal(proxyTakeMoney);
            BigDecimal center = new BigDecimal(centerTakeMoney);
            BigDecimal bigDecimal = user.add(proxy).add(center).setScale(2, BigDecimal.ROUND_HALF_UP);
            map.put("takeMoney", bigDecimal.doubleValue());
        }


        //充值金额
        if(adminInfo.getTaiGroupId() == null){
            map.put("chargeMoney", null);
        }else{
            String chargeMoney = tSystemAccountMapper.getChargeMoney(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("chargeMoney", chargeMoney);
        }


        //今日已完成订单
        if(adminInfo.getTaiGroupId() == null){
            map.put("todayOrderCount", null);
        }else{
            String todayOrderCount = tOrderInfoMapper.getTodayOrderCount(adminInfo.getTaiGroupId(), adminInfo.getTaiRelationId());
            map.put("todayOrderCount", todayOrderCount);
        }


        return map;
    }

    /**
     * 分配权利金作为佣金给运营中心，代理，和经纪人
     *
     * @param userId：用户ID
     * @param orderId：订单ID
     * @param optionMoney：权利金
     */
    @Transactional
    @Override
    public void splitOptionMoney(Integer userId, Integer orderId, Double optionMoney) throws Exception {
        //先得到用户
        TUserInfo tUserInfo = tUserInfoMapper.selectByPrimaryKey(userId);
        if (tUserInfo == null) {
            return;
        }
        Integer tuiShareType = tUserInfo.getTuiShareType();
        Integer tuiShareId = tUserInfo.getTuiShareId();

        //判断用户的上级是什么
        //如果是平台，直接把权利金存到管理员的余额中
        //获取系统设置中经纪人的佣金比例
        //经纪人，权利金*佣金比例   存到经纪人余额
        //每分配一次佣金都往系统账目表存一条记录
        List<TAdminBalance> tAdminBalances = tAdminBalanceMapper.selectAll();
        if (tAdminBalances.size() == 0) {
            TAdminBalance tAdminBalance = new TAdminBalance();
            tAdminBalance.setTabMoney(0.0);
            tAdminBalanceMapper.insertSelective(tAdminBalance);
            tAdminBalances = tAdminBalanceMapper.selectAll();
        }
        //平台账户余额
        TAdminBalance tAdminBalance = tAdminBalances.get(0);
        switch (tuiShareType) {
            case 0://平台
                //获得订单信息
                TOrderInfo tOrderInfo = tOrderInfoMapper.selectByPrimaryKey(orderId);
                //如果运营中心ID不为空，则把佣金给运营中心，并从权利金中减去相应的佣金
                if(tOrderInfo.getToiCenterId() != null && tOrderInfo.getToiCenterId() != 0){
                    TOperationCenter tOperationCenterD = tOperationCenterMapper.selectByPrimaryKey(tOrderInfo.getToiCenterId());
                    //系统账目
                    TSystemAccount tSystemAccountC = new TSystemAccount(5,1,tOrderInfo.getToiCenterId(),orderId,optionMoney,tOperationCenterD.getTocBalance(),
                            tOperationCenterD.getTocBalance()+optionMoney*tOperationCenterD.getTocRatio(),1,"获得平台用户佣金");
                    tSystemAccountMapper.insertSelective(tSystemAccountC);
                    tOperationCenterD.setTocBalance(tOperationCenterD.getTocBalance()+optionMoney*tOperationCenterD.getTocRatio());
                    tOperationCenterMapper.updateByPrimaryKeySelective(tOperationCenterD);
                    optionMoney = optionMoney * (1-tOperationCenterD.getTocRatio());
                }

                //系统账目
//                TSystemAccount tSystemAccountC = new TSystemAccount(5, 0, tuiShareId, orderId, optionMoney, tAdminBalance.getTabMoney(),
//                        tAdminBalance.getTabMoney() + optionMoney, 1, "获得平台用户佣金");
//                tSystemAccountMapper.insertSelective(tSystemAccountC);

                //更新余额
                tAdminBalance.setTabMoney(tAdminBalance.getTabMoney() + optionMoney);
                tAdminBalanceMapper.updateByPrimaryKeySelective(tAdminBalance);
                break;
            case 1://代理
                //代理获得---------------------------
                TProxyInfo tProxyInfo = tProxyInfoMapper.selectByPrimaryKey(tuiShareId);
                //运营中心获得-------------------------
                TOperationCenter tOperationCenterP = tOperationCenterMapper.selectByPrimaryKey(tProxyInfo.getTpiHeadId());

                //总共的佣金
                Double allCommision = optionMoney * tOperationCenterP.getTocRatio();

                //代理的佣金
                Double proxyCom = roundTwo(allCommision * tProxyInfo.getTpiRatio());
                Double centerCom = allCommision - proxyCom;

                //添加代理系统账目
                TSystemAccount tSystemAccountP = new TSystemAccount(5, 2, tuiShareId, orderId, proxyCom, tProxyInfo.getTpiBalance(),
                        tProxyInfo.getTpiBalance() + proxyCom, 1, "获得代理用户佣金");
                tSystemAccountMapper.insertSelective(tSystemAccountP);
                //更新代理余额
                tProxyInfo.setTpiBalance(tProxyInfo.getTpiBalance() + proxyCom);
                tProxyInfoMapper.updateByPrimaryKeySelective(tProxyInfo);


                //添加运营中心系统账目
                TSystemAccount tSystemAccountPC = new TSystemAccount(5, 1, tProxyInfo.getTpiHeadId(), orderId, centerCom,
                        tOperationCenterP.getTocBalance(), tOperationCenterP.getTocBalance() + centerCom, 1, "获得代理用户佣金");
                tSystemAccountMapper.insertSelective(tSystemAccountPC);
                //更新运营中心余额
                tOperationCenterP.setTocBalance(tOperationCenterP.getTocBalance() + centerCom);
                tOperationCenterMapper.updateByPrimaryKeySelective(tOperationCenterP);

                //更新管理员权利金-------------------------------
                optionMoney = optionMoney - allCommision;

                //系统账目
//                TSystemAccount tSystemAccountPt = new TSystemAccount(5, 0, 0, orderId, optionMoney, tAdminBalance.getTabMoney(),
//                        tAdminBalance.getTabMoney() + optionMoney, 1, "获得代理用户佣金");
//                tSystemAccountMapper.insertSelective(tSystemAccountPt);

                //更新余额
                tAdminBalance.setTabMoney(tAdminBalance.getTabMoney() + optionMoney);
                tAdminBalanceMapper.updateByPrimaryKeySelective(tAdminBalance);

                break;
            case 2://经纪人--------------------------
                TUserInfo tUserInfoJJR = tUserInfoMapper.selectByPrimaryKey(tuiShareId);
                //获取系统设置中经纪人的佣金比例
                TSystemConfig tSystemConfig = tSystemConfigMapper.selectByKey("user_option_money");
                Double ratio = Double.valueOf(tSystemConfig.getTscValue());

                //代理获得-------------------------------
                TProxyInfo tProxyInfoJ = tProxyInfoMapper.selectByPrimaryKey(tUserInfoJJR.getTuiShareId());
                //运营中心获得-----------------------------
                TOperationCenter tOperationCenterJ = tOperationCenterMapper.selectByPrimaryKey(tProxyInfoJ.getTpiHeadId());

                //总共的佣金
                Double threeCommision = optionMoney * tOperationCenterJ.getTocRatio();
                //代理的佣金
                Double proxy = roundTwo(threeCommision * tProxyInfoJ.getTpiRatio());
                Double center = threeCommision - proxy;

                //经济人从代理中的佣金中获得
                Double jingjiren = roundTwo(proxy * ratio);
                proxy = proxy - jingjiren;

                //添加系统账目
                TSystemAccount tSystemAccountJj = new TSystemAccount(5, 3, tuiShareId, orderId, jingjiren, tUserInfoJJR.getTuiBalance(),
                        tUserInfoJJR.getTuiBalance() + jingjiren, 1, "获得经纪人用户佣金");
                tSystemAccountMapper.insertSelective(tSystemAccountJj);
                //更新经纪人余额
                tUserInfoJJR.setTuiBalance(tUserInfoJJR.getTuiBalance() + jingjiren);
                tUserInfoMapper.updateByPrimaryKeySelective(tUserInfoJJR);


                //添加代理系统账目
                TSystemAccount tSystemAccountJ = new TSystemAccount(5, 2, tUserInfoJJR.getTuiShareId(), orderId, proxy, tProxyInfoJ.getTpiBalance(),
                        tProxyInfoJ.getTpiBalance() + proxy, 1, "获得经纪人用户佣金");
                tSystemAccountMapper.insertSelective(tSystemAccountJ);
                //更新代理余额
                tProxyInfoJ.setTpiBalance(tProxyInfoJ.getTpiBalance() + proxy);
                tProxyInfoMapper.updateByPrimaryKeySelective(tProxyInfoJ);


                //添加运营中心系统账目
                TSystemAccount tSystemAccountJC = new TSystemAccount(5, 1, tProxyInfoJ.getTpiHeadId(), orderId, center,
                        tOperationCenterJ.getTocBalance(), tOperationCenterJ.getTocBalance() + center, 1, "获得经纪人用户佣金");
                tSystemAccountMapper.insertSelective(tSystemAccountJC);
                //更新运营中心余额
                tOperationCenterJ.setTocBalance(tOperationCenterJ.getTocBalance() + center);
                tOperationCenterMapper.updateByPrimaryKeySelective(tOperationCenterJ);

                //更新权利金-------------------------------
                optionMoney = optionMoney - threeCommision;

                //系统账目
//                TSystemAccount tSystemAccountJt = new TSystemAccount(5, 0, 0, orderId, optionMoney, tAdminBalance.getTabMoney(),
//                        tAdminBalance.getTabMoney() + optionMoney, 1, "获得经纪人用户佣金");
//                tSystemAccountMapper.insertSelective(tSystemAccountJt);

                //更新余额
                tAdminBalance.setTabMoney(tAdminBalance.getTabMoney() + optionMoney);
                tAdminBalanceMapper.updateByPrimaryKeySelective(tAdminBalance);
                break;
                default:
                    break;
        }


    }

    public double roundTwo(double x){
        BigDecimal   b   =   new BigDecimal(x);
        return  b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    @Override
    public Map<String, Object> getOderInfoById(Integer toiId) {
        Map<String, Object> map = new HashMap<>();
        List<TOrderInfo> orderList = tOrderInfoMapper.getOderInfoById(toiId);
        map.put("data",orderList.get(0));
        return map;
    }

    @Override
    public Map<String, Object> selectOtherMap(JSONObject jsonObject, Integer type) {
        TAdminInfo adminInfo = BackAdminLogin.getAdminInfo();
        if(adminInfo.getTaiGroupId() == null){
            Map<String, Object> map = new HashMap<>();
            map.put("sumProfit",null);
            map.put("sumOptionMoney",null);
            map.put("sumBalance",null);
            return map;
        }
        return tOrderInfoMapper.selectOtherMap(
                jsonObject.getString("tuiPhone"),
                jsonObject.getString("startTime"),
                jsonObject.getString("endTime"),
                jsonObject.getInteger("centerId"),
                jsonObject.getInteger("tProxyInfoId"),
                jsonObject.getInteger("tuiUserId"),
                jsonObject.getString("stockIdName"),
                jsonObject.getInteger("toiStatus"),
                type,
                adminInfo.getTaiGroupId(),
                adminInfo.getTaiRelationId());
    }
}
